package org.kkk.sandbox.sandbox.impl;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import cn.hutool.core.io.FileUtil;
import org.kkk.sandbox.enums.JudgeInfoMessageEnum;
import org.kkk.sandbox.model.*;
import org.kkk.sandbox.sandbox.CodeSandbox;
import org.kkk.sandbox.utils.ProcessUtils;

public class JavaNativeCodeSandbox implements CodeSandbox {
    private static final String FILE_STORAGE_DIR="kkk_java";
    private static final String CLASS_NAME="Main.java";

    public static void main(String[] args) throws IOException {
        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream("D:\\Users\\sandbox\\src\\main\\resources\\test\\Main.java")));
        String content="";
        String s="";
        while ((s=bufferedReader.readLine())!=null)
        {
            content+=s+ System.lineSeparator();
        }
        executeCodeRequest.setInputList(new ArrayList<String>(List.of("4\n" +
                "1 2 3 4\n")));
        executeCodeRequest.setCode(content);
        executeCodeRequest.setLanguage("java");
        executeCodeRequest.setJudgeInfo(new JudgeInfo("",60L,60L));
        new JavaNativeCodeSandbox().executeCode(executeCodeRequest);
    }
    @Override
    public  ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        ExecuteCodeResponse response = new ExecuteCodeResponse();
        String rootPath=System.getProperty("user.dir");
        String rootDir= rootPath+File.separator+FILE_STORAGE_DIR;
        if(FileUtil.exist(rootDir))
        {
            FileUtil.mkdir(rootDir);
        }
        String codePath=rootDir+File.separator+ UUID.randomUUID();
        String classPath=codePath+File.separator+CLASS_NAME;
        FileUtil.writeString(executeCodeRequest.getCode(),classPath,StandardCharsets.UTF_8);
            //编译
        try {
            Process process = Runtime.getRuntime().exec("javac -encoding utf-8 "+classPath);
            ProcessExecuteMessage processExecuteMessage = ProcessUtils.processExecute(process);
            if(ProcessUtils.isSuccess(processExecuteMessage.getExitCode()))
            {
                ArrayList<String> outputList = new ArrayList<>();
                ArrayList<CaseExecuteInfo> caseExecuteInfo = new ArrayList<>();
                //执行代码
                for (String s : executeCodeRequest.getInputList()) {
                    //遍历每一个实例
                    String command=String.format("java -Dfile.encoding=UTF-8 -cp %s Main",codePath);
                    Process codeExecProcess = Runtime.getRuntime().exec(command);
                    ProcessExecuteMessage executeMessage = ProcessUtils.runInteractProcess(codeExecProcess, s,executeCodeRequest.getJudgeInfo());
                    //将结果封装成request
                    if(ProcessUtils.isSuccess(executeMessage.getExitCode()))
                    {
                        //判题机通过
                        caseExecuteInfo.add(new CaseExecuteInfo(executeMessage.getExecMemory(),executeMessage.getExecTime(), JudgeInfoMessageEnum.ACCEPTED.getCode()));
                        outputList.add(executeMessage.getMessage());
                        System.out.println(executeMessage);
                    }
                  else{
                      //失败了 todo 捕获失败
                        System.err.println(executeMessage.getExitCode());
                        System.err.println(executeMessage.getMessage());
                    }
                }
                response.setOutputList(outputList);
            }
            else{
                //编译失败
                response.setOutputList(null);
                response.setCaseExecuteInfo(null);
                response.setMessage("编译失败");
                System.err.println(processExecuteMessage.getMessage());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return null;
    }
}
